package com.atues.tree;

import java.util.HashMap;
import java.util.Map;

public class Bt {

    class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;
        TreeNode() {}
        TreeNode(int val) { this.val = val; }
        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

    Map<Integer, Integer> inorderIndexMap = new HashMap<>();
    public TreeNode buildTree(int[] preorder, int[] inorder) {
        for (int i = 0; i < inorder.length; i++) {
            inorderIndexMap.put(inorder[i], i);
        }
        return buildTree1(preorder, 0, preorder.length - 1, 0);
    }

    private TreeNode buildTree1(int[] preorder, int root, int left, int right) {
        if (root > preorder.length - 1 || left > right) {
            return null;
        }
        TreeNode node = new TreeNode(preorder[root]);
        int index = inorderIndexMap.get(preorder[root]);
        node.left = buildTree1(preorder, root + 1, left, index - 1);
        node.right = buildTree1(preorder, root + index - left + 1, index + 1, right);
        return node;
    }


}
